package com.test.application.exam;

import cn.hutool.core.collection.ListUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述: TODO
 * 作者: yanruizhi
 * 时间: 2024/7/18 23:04
 */
public class MergeUtil {
/*    红富士， [红色, 纯天然, 很甜]，10个
    红富士， [很甜, 红色, 纯天然]，2个
    红富士， [纯天然, 红色]，5个
    小金苹果， [纯天然, 红色]，20个
    */
    public static List<Goods> goodsList = new ArrayList<>();
    static {
        Goods g1 = new Goods("红富士", ListUtil.of("红色", "纯天然", "很甜"), 10);
        Goods g2= new Goods("红富士", ListUtil.of("很甜", "红色", "纯天然"), 2);
        Goods g3= new Goods("红富士", ListUtil.of("纯天然", "红色"), 5);
        Goods g4= new Goods("小金苹果", ListUtil.of("纯天然", "红色"), 20);
        goodsList.add(g1);
        goodsList.add(g2);
        goodsList.add(g3);
        goodsList.add(g4);
    }
    public static List<Goods> mergeGoods(List<Goods> goodsList) {
        Map<CompositeKey, Integer> mergedMap = new HashMap<>();

        for (Goods good : goodsList) {
            CompositeKey key = new CompositeKey(good.name, new HashSet<>(good.attrList));
            mergedMap.merge(key, good.count, Integer::sum);
        }
        List<Goods> collect = mergedMap.entrySet().stream().map(entry -> new Goods(entry.getKey().name, entry.getKey().attrList, entry.getValue())).collect(Collectors.toList());
            collect.forEach(System.out::println);

        return collect;
    }

    public static void main(String[] args) {
        mergeGoods(goodsList);
    }
}
